package com.yupi.springbootinit.service.workflow;

import com.yupi.springbootinit.mapper.WorkflowTaskMapper;
import com.yupi.springbootinit.model.entity.Department;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.entity.WorkflowTask;
import com.yupi.springbootinit.model.vo.WorkflowTaskVO;
import com.yupi.springbootinit.service.DepartmentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.yupi.springbootinit.service.workflow.WorkflowTaskConstants.*;

/**
 * 工作流任务权限服务
 * 负责任务权限校验和权限信息计算
 */
@Slf4j
@Service
public class WorkflowTaskPermissionService {

    @Resource
    private WorkflowTaskMapper workflowTaskMapper;

    @Resource
    private DepartmentService departmentService;

    /**
     * 检查用户是否可以认领任务
     *
     * @param taskId 任务ID
     * @param user 当前用户
     * @return true=可以认领，false=不可以
     */
    public boolean checkCanClaim(Long taskId, User user) {
        if (taskId == null || user == null) {
            return false;
        }

        WorkflowTask task = workflowTaskMapper.selectById(taskId);
        if (task == null || (task.getIsDelete() != null && task.getIsDelete() == 1)) {
            log.warn("任务不存在或已删除, taskId={}", taskId);
            return false;
        }

        // 1. 检查部门权限：任务必须属于当前用户部门
        if (!task.getDepartmentId().equals(user.getDepartmentId())) {
            log.warn("用户部门不匹配, taskDeptId={}, userDeptId={}", task.getDepartmentId(), user.getDepartmentId());
            return false;
        }

        // 2. PUBLISH_BATCH类型任务不允许认领
        if (TASK_TYPE_PUBLISH_BATCH.equals(task.getTaskType())) {
            log.warn("PUBLISH_BATCH类型任务不允许认领, taskId={}", taskId);
            return false;
        }

        // 3. 任务必须是待认领状态
        if (!STATUS_PENDING.equals(task.getTaskStatus())) {
            log.warn("任务状态不允许认领, taskId={}, status={}", taskId, task.getTaskStatus());
            return false;
        }

        // 4. 任务不能已被认领
        if (task.getClaimedBy() != null) {
            log.warn("任务已被认领, taskId={}, claimedBy={}", taskId, task.getClaimedBy());
            return false;
        }

        return true;
    }

    /**
     * 检查用户是否可以处理任务
     *
     * @param taskId 任务ID
     * @param user 当前用户
     * @return true=可以处理，false=不可以
     */
    public boolean checkCanProcess(Long taskId, User user) {
        if (taskId == null || user == null) {
            return false;
        }

        WorkflowTask task = workflowTaskMapper.selectById(taskId);
        if (task == null || (task.getIsDelete() != null && task.getIsDelete() == 1)) {
            return false;
        }

        // 1. 检查部门权限
        if (!task.getDepartmentId().equals(user.getDepartmentId())) {
            log.warn("用户部门不匹配, taskDeptId={}, userDeptId={}", task.getDepartmentId(), user.getDepartmentId());
            return false;
        }

        // 2. 任务必须已被当前用户认领
        if (task.getClaimedBy() == null || !task.getClaimedBy().equals(user.getId())) {
            log.warn("任务未被当前用户认领, taskId={}, claimedBy={}, userId={}", taskId, task.getClaimedBy(), user.getId());
            return false;
        }

        // 3. 任务状态必须是待处理或进行中
        if (!STATUS_PENDING.equals(task.getTaskStatus()) && !STATUS_IN_PROGRESS.equals(task.getTaskStatus())) {
            log.warn("任务状态不允许处理, taskId={}, status={}", taskId, task.getTaskStatus());
            return false;
        }

        return true;
    }

    /**
     * 检查用户是否可以查看任务附件
     *
     * @param taskId 任务ID
     * @param user 当前用户
     * @return true=可以查看，false=不可以
     */
    public boolean checkCanViewAttachment(Long taskId, User user) {
        if (taskId == null || user == null) {
            return false;
        }

        WorkflowTask task = workflowTaskMapper.selectById(taskId);
        if (task == null || (task.getIsDelete() != null && task.getIsDelete() == 1)) {
            return false;
        }

        // 目前仅工程部（GC001）可查看销售订单附件
        // 如需扩展其他部门权限，在此添加规则
        if (user.getDepartmentId() == null) {
            return false;
        }

        // 获取用户的部门编码
        Department department = departmentService.getById(user.getDepartmentId());
        if (department == null) {
            return false;
        }

        return "GC001".equals(department.getDepartmentCode()) && "SALES_ORDER".equals(task.getBizType());
    }

    /**
     * 检查用户是否可以完成任务
     *
     * @param taskId 任务ID
     * @param user 当前用户
     * @return true=可以完成，false=不可以
     */
    public boolean checkCanComplete(Long taskId, User user) {
        if (taskId == null || user == null) {
            return false;
        }

        WorkflowTask task = workflowTaskMapper.selectById(taskId);
        if (task == null || (task.getIsDelete() != null && task.getIsDelete() == 1)) {
            return false;
        }

        // 1. 检查部门权限
        if (!task.getDepartmentId().equals(user.getDepartmentId())) {
            log.warn("用户部门不匹配, taskDeptId={}, userDeptId={}", task.getDepartmentId(), user.getDepartmentId());
            return false;
        }

        // 2. 任务必须已被当前用户认领
        if (task.getClaimedBy() == null || !task.getClaimedBy().equals(user.getId())) {
            log.warn("任务未被当前用户认领, taskId={}, claimedBy={}, userId={}", taskId, task.getClaimedBy(), user.getId());
            return false;
        }

        // 3. 任务状态必须是进行中
        if (!STATUS_IN_PROGRESS.equals(task.getTaskStatus())) {
            log.warn("任务状态不允许完成, taskId={}, status={}", taskId, task.getTaskStatus());
            return false;
        }

        return true;
    }

    /**
     * 为任务VO计算并填充权限信息
     *
     * @param taskVO 任务VO对象
     * @param currentUser 当前用户
     */
    public void calculateTaskPermissions(WorkflowTaskVO taskVO, User currentUser) {
        if (taskVO == null || currentUser == null) {
            return;
        }

        // 初始化所有权限为false
        taskVO.setCanClaim(false);
        taskVO.setCanProcess(false);
        taskVO.setCanViewAttachment(false);
        taskVO.setCanComplete(false);
        taskVO.setCanViewDetail(true); // 详情默认可查看
        taskVO.setAvailableActions(new ArrayList<>());

        // 检查部门权限（核心校验）
        if (!taskVO.getDepartmentId().equals(currentUser.getDepartmentId())) {
            taskVO.setDisabledReason("该任务不属于您的部门");
            taskVO.setAvailableActions(List.of("VIEW_DETAIL")); // 只能查看详情
            return;
        }

        // 计算认领权限
        boolean isPending = STATUS_PENDING.equals(taskVO.getTaskStatus());
        boolean isUnclaimed = taskVO.getClaimedBy() == null;
        boolean isPublishBatch = TASK_TYPE_PUBLISH_BATCH.equals(taskVO.getTaskType());
        
        if (isPending && isUnclaimed && !isPublishBatch) {
            taskVO.setCanClaim(true);
            taskVO.getAvailableActions().add("CLAIM");
        } else if (isPublishBatch) {
            taskVO.setDisabledReason("批次发布任务由系统自动完成");
        } else if (!isUnclaimed) {
            taskVO.setDisabledReason("任务已被" + taskVO.getClaimedByName() + "认领");
        }

        // 计算处理权限
        boolean isClaimedByCurrentUser = taskVO.getClaimedBy() != null && 
                                         taskVO.getClaimedBy().equals(currentUser.getId());
        boolean canOperate = (isPending || STATUS_IN_PROGRESS.equals(taskVO.getTaskStatus())) && 
                            isClaimedByCurrentUser;
        
        if (canOperate) {
            taskVO.setCanProcess(true);
            taskVO.getAvailableActions().add("PROCESS");
            
            // 设置操作提示
            if (TASK_TYPE_CREATE_PROCESS_SHEET.equals(taskVO.getTaskType())) {
                taskVO.setActionHint("点击继续处理跳转到工艺单创建页面");
            } else if (TASK_TYPE_CREATE_SCHEDULE.equals(taskVO.getTaskType())) {
                taskVO.setActionHint("点击继续处理跳转到PMC排期页面");
            }
        }

        // 计算完成权限
        if (STATUS_IN_PROGRESS.equals(taskVO.getTaskStatus()) && isClaimedByCurrentUser) {
            taskVO.setCanComplete(true);
            taskVO.getAvailableActions().add("COMPLETE");
        }

        // 计算附件查看权限
        if (currentUser.getDepartmentId() != null) {
            Department department = departmentService.getById(currentUser.getDepartmentId());
            if (department != null && "GC001".equals(department.getDepartmentCode()) && 
                "SALES_ORDER".equals(taskVO.getBizType())) {
                taskVO.setCanViewAttachment(true);
                taskVO.getAvailableActions().add("VIEW_ATTACHMENT");
            }
        }

        // 详情始终可查看
        taskVO.getAvailableActions().add("VIEW_DETAIL");
    }
}
